package cn.symbio.basic.service.impl;

import cn.symbio.basic.config.BussinessException;
import cn.symbio.basic.constant.BaseConstant;
import cn.symbio.basic.dto.EmailRegisterDto;
import cn.symbio.basic.dto.PhoneRegisterDto;
import cn.symbio.basic.service.IRegisterService;
import cn.symbio.basic.util.MD5Utils;
import cn.symbio.basic.util.StrUtils;
import cn.symbio.user.domain.Logininfo;
import cn.symbio.user.domain.User;
import cn.symbio.user.mapper.LogininfoMapper;
import cn.symbio.user.mapper.UserMapper;
import cn.symbio.user.service.ILogininfoService;
import cn.symbio.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Date;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机注册
     * @param dto
     */
    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        // 校验
        verifyPhone(dto);
        // user赋值
        User user = userCopyPhoneDto(dto);
        // copy logininfo并添加
        Logininfo logininfo = logininfoCopyUser(user);
        logininfo.setType(1);
        logininfoMapper.add(logininfo);
        // 添加登录id
        user.setLogininfoId(logininfo.getId());
        user.setCreatetime(new Date());
        // 添加到数据库
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     * @param dto
     */
    @Override
    public void emailRegister(EmailRegisterDto dto) {
        // 校验
        verifyEmail(dto);
        // user数据拷贝
        User user = userCopyEmailDto(dto);
        // logininfo拷贝
        Logininfo logininfo = logininfoCopyUser(user);
        logininfo.setType(1);
        logininfoMapper.add(logininfo);
        // 是指logininfo_id
        user.setCreatetime(new Date());
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    // Logininfo赋值
    public static Logininfo logininfoCopyUser(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;
    }


    // User对象赋值
    public static User userCopyPhoneDto(PhoneRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 加盐密码
        String saltPassword = salt + dto.getPassword();
        // MD5加密
        String MDSaltPassword = MD5Utils.encrypByMd5(saltPassword);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(MDSaltPassword)
                .build();
    }
    // User对象赋值
    public static User userCopyEmailDto(EmailRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 加盐密码
        String saltPassword = salt + dto.getEmailPassword();
        // MD5加密
        String MDSaltPassword = MD5Utils.encrypByMd5(saltPassword);
        return User
                .builder()
                .username(dto.getEmail())
                .email(dto.getEmail())
                .salt(salt)
                .password(MDSaltPassword)
                .build();
    }


    /**
     * 手机注册校验
     */
    private void verifyPhone(PhoneRegisterDto dto) {
        // 空校验
        // 判断两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！！！");
        }
        // 判断短信验证码是否正确和两次手机号是否正确
        String phoneCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        if (StringUtils.isBlank(phoneCode)) {
            throw new BussinessException("验证码错误！！！");
        }
        // 取出短信验证码进行判断
        String[] split = phoneCode.split(":");
        String code = split[0];
        if (!code.equals(dto.getSmsCodeValue())) {
            throw new BussinessException("手机验证码错误！！！");
        }
        // 判断手机号是否存在
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user) {
            throw new BussinessException("请登录，傻杯！！！");
        }
    }

    /**
     * 邮箱注册校验
     * @param dto
     */
    private void verifyEmail(EmailRegisterDto dto) {
        // 空校验
        // 判断两次密码是否一致
        if (!dto.getEmailPassword().equals(dto.getEmailPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！！！");
        }
        // 判断短信验证码是否正确和两次邮箱是否正确
        String emailCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getEmail()));
        if (StringUtils.isBlank(emailCode)) {
            throw new BussinessException("验证码错误！！！");
        }
        // 取出短信验证码进行判断
        String[] split = emailCode.split(":");
        String code = split[0];
        if (!code.equals(dto.getEmailCodeValue())) {
            throw new BussinessException("邮箱验证码错误！！！");
        }
        // 判断邮箱是否存在
        User user = userMapper.findByEmail(dto.getEmail());
        if (null != user) {
            throw new BussinessException("请登录，傻杯！！！");
        }
    }
}
